package com.dianban.controller.nengliang;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.FacePayStoreConsumeLog;
import com.dianban.service.FacePayConfigService;
import com.dianban.service.FacePayStoreConsumeLogService;
import com.dianban.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Api(value = "ApiConsumeController", description = "服务消费控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/consume/")
public class ApiConsumeController extends BaseController {

    @Autowired
    private FacePayConfigService facePayConfigService;
    @Autowired
    private FacePayStoreConsumeLogService facePayStoreConsumeLogService;

    @ApiOperation(notes = "hasService", httpMethod = "GET", value = "获取是否在提供消费服务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "设备sn", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "hasService", method = RequestMethod.GET)
    public ResultVo hasService(String sn, HttpServletRequest request, HttpServletResponse response) {
        Boolean hasService = false;
        try {
            // 根据设备sn查找到门店id
            FacePayConfig facePayConfig = facePayConfigService.findByName(sn);
            if (facePayConfig == null) {
                return ResultVo.error(ResultCode.ERROR, "找不到该设备sn");
            }
            Long storeId = facePayConfig.getStoreId();
            Date nowTime = new Date();
            Date beforeTime = DateUtils.addMinutes(nowTime, -45);
            // 查看该门店当前45分钟内，是否有消费订单并且还在服务中
            List<FacePayStoreConsumeLog> consumeLogList = facePayStoreConsumeLogService.find(storeId, beforeTime.getTime() / 1000, nowTime.getTime() / 1000);
            if (!CollectionUtils.isEmpty(consumeLogList)) {
                hasService = true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(hasService, "获取成功");
    }
}
